<?php

namespace App\Http\Controllers;

use App\Services\SubService;
use App\Store;
use App\StoresInfo;
use App\Subsidy;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StoreController extends BaseController
{
    /**
     * 入驻
     * @return \Illuminate\Http\JsonResponse
     */
    public function settleIn(): \Illuminate\Http\JsonResponse
    {
        $this->uid = \session('uid');
        $user = DB::table('users')->where('id', $this->uid)->first();
        if( $user->type != 1 ){
            DB::table('users')->where('id', $this->uid)->update(['type'=>1, 'updated_at'=>getDt(), 'merchant_date'=>getDt()]);
        }

        return returnJson();
    }

    /**
     * 获取补贴列表
     */
    public function getSub(Request $request): \Illuminate\Http\JsonResponse
    {
        $this->uid = \session('uid')??0;
//        分类id
        $category = $request->cate??0;

//        排序方式:0-距离，1-返现金额，2-返现比例，3-不要评价
        $sort = $request->sort??0;
//        搜索标题
        $title = $request->key??"";
//        分页页码
        $page = $request->page??1;
//        是否推荐:0-否，1-是
        $recommend = $request->recommend??0;

        $lat = $request->lat??'';//纬度
        $lnt = $request->lnt??'';//经度
        if( !$this->uid ){
            $page = 1;
            $size = 5;
        }else{
            $size = 0;
        }

        $Subsidy = new Subsidy();
        $list = $Subsidy->getSub($category, $sort, $title, $recommend, $page, $lat, $lnt, $size);

        return returnJson(0, '', $list);
    }

    /**
     * 获取当前用户的店铺信息
     */
    public function getInfo()
    {
        $this->uid = \session('uid');
        $list = DB::table('stores')->where('uid', $this->uid)->where('is_deleted', 0)->get();
        foreach ($list as &$item) {
            $item->storeInfo = DB::table('stores_info')->where('store_id', $item->id)->get();
        }
        return returnJson(0, "", $list);
    }

    /**
     * 获取指定店铺信息
     */
    public function getInfoById(Request $request)
    {
        $this->uid = \session('uid');
        $id = $request->id;
        $data = DB::table('stores')->where('id', $id)->first();
        $data->storeInfo = DB::table('stores_info')->where('store_id', $id)->get();
        $cateArr = explode(',',$data->cate_ids);
        $cate_names = "";
        foreach ($cateArr as $item){
            $cate_name = DB::table('categorys')->where('id', $item)->value('title');
            $cate_names.= $cate_name.'，';
        }

        $data->cate_name = trim($cate_names,'，');
        return returnJson(0, "", $data);
    }

    /**
     * 获取当前用户的店铺列表
     */
    public function getStoreInfoList()
    {
        $this->uid = \session('uid');
        $list = DB::table('stores_info')
            ->join('stores', 'stores_info.store_id', '=', 'stores.id')
            ->select("stores_info.*","stores.imgurl","stores.address","stores.address_detail")
            ->where('stores_info.uid', $this->uid)->where('stores.is_deleted', 0)->get();

        if($list){
            foreach ($list as &$item){
                $item->select = false;
            }
        }
        return returnJson(0, "", $list);
    }

    /**
     * 获取运营品类
     */
    public function getCate(){
        $list = DB::table('categorys')->select("title as label","id as value")->get();
        foreach ($list as &$item){
            $item->active = false;
        }
        return returnJson(0, "", $list);
    }

    /**
     * 获取当前用户的店铺统计
     */
    public function getStoreStatistics()
    {
        $this->uid = \session('uid');
        //待复审
        $data['recheck'] = \DB::table('users_orders')->where('store_uid', $this->uid)->whereIn('status', [35,40])->count();
        //驳回
        $data['reject'] = \DB::table('users_orders')->where('store_uid', $this->uid)->whereIn('status', [30,32])->orWhere([['status', 10], ['is_merchant_do', 1]])->count();
        //已完成
        $data['done'] = \DB::table('users_orders')->where('store_uid', $this->uid)->where('status', 50)->count();
        //发布中
        $data['publish'] = \DB::table('subsidy')->where('uid', $this->uid)->whereIn('status', [0,1])->where('is_deleted', 0)->count();
        //已过期
        $data['overdue'] = \DB::table('subsidy')->where('uid', $this->uid)->where('status', 2)->where('is_deleted', 0)->count();
        //今日订单金额
        $data['amount'] = \DB::table('users_orders')->where('store_uid', $this->uid)->whereDate('created_at', date('Y-m-d'))->whereIn('status', [25, 30,35,40,50])->sum('amount');
        //今日返现金额
        $data['returnAmount'] = \DB::table('users_orders')->where('store_uid', $this->uid)->whereDate('created_at', date('Y-m-d'))->where('status', 50)->sum('settle_amount');
        //今日订单数量
        $data['todayOrderNum'] = \DB::table('users_orders')->where('store_uid', $this->uid)->whereDate('created_at', date('Y-m-d'))->whereIn('status', [25, 30,35,40,50])->count();

        //昨日订单金额
        $data['tomoAmount'] = \DB::table('users_orders')->where('store_uid', $this->uid)->whereDate('created_at', date('Y-m-d', time()-3600*24))->whereIn('status', [25, 30,35,40,50])->sum('amount');
        //昨日返现金额
        $data['tomoReturnAmount'] = \DB::table('users_orders')->where('store_uid', $this->uid)->whereDate('created_at', date('Y-m-d', time()-3600*24))->where('status', 50)->sum('settle_amount');
        //昨日订单数量
        $data['tomoOrderNum'] = \DB::table('users_orders')->where('store_uid', $this->uid)->whereDate('created_at', date('Y-m-d', time()-3600*24))->whereIn('status', [25, 30,35,40,50])->count();

        //是否有昨日待复审订单即将逾期
        $data['tomoRecheckOrder'] = \DB::table('users_orders')->where('store_uid', $this->uid)->whereIn('status', [35,40])->where('created_at', '<', date('Y-m-d 00:00:00'))->count();
        //是否待结算逾期:冻结时间存在即逾期，null即没有逾期订单
        $data['isNotSettle'] = \DB::table('users')->where('id', $this->uid)->value('frozen_date');

        return returnJson(0, "", $data);
    }

    /**
     * 获取当前服务费
     */
    public function getServiceFee()
    {
        //基础服务费
        $data['fee'] = \DB::table('config')->where('key', 'fee')->value('value');
        //当前折扣
        $data['nowFee'] = \DB::table('fee_activity')->where('start', '<', \getDt())->where('end', '>', \getDt())->orderBy('id', 'desc')->value('discount');
        
        return returnJson(0, "", $data);
    }



    /**
     * 更新用户店铺信息
     * @param Request $request
     */
    public function save(Request $request)
    {
        $this->uid = \session('uid');
        $id = intval($request->id);
        $uid = $this->uid;
        $linkname = $request->linkname;
        $cate_ids = $request->cate_ids;
        $phone = $request->phone;
        $start_time = $request->start_time;
        $end_time = $request->end_time;
        $address = $request->address;
        $address_detail = $request->address_detail;
        $lat = $request->lat;
        $lnt = $request->lnt;
        $imgurl = $request->imgurl;
        $info = json_decode($request->info,true);//平台店铺信息：['meiTuan'=>['title'=>'乐淘点'], 'eLeMe'=>['title'=>'乐淘点']]
//        $info = [];//饿了么，美团店铺信息：数组
        try {
            DB::beginTransaction();
            if( $id ){
                $storeModle = Store::find($id);
            }else{
                $storeModle = new Store();
            }

            $user = DB::table('users')->where('id', $this->uid)->first();
            if( !$user ){
                return returnJson(1, "商户信息有误");
            }

            if ( !isset($info['eLeMe']) && !isset($info['meiTuan']) ){
                return returnJson(1, "请至少选择一个外卖店铺");
            }

            // 插入或更新用户店铺基础信息
            $storeData = [
                'uid' => $uid,
                'linkname' => $linkname,
                'phone' => $phone, 'start_time' => $start_time, 'end_time' => $end_time, 'address' => $address, 'address_detail' => $address_detail,
                'cate_ids' => $cate_ids,
                'lat' => $lat,
                'lnt' => $lnt,
                'imgurl' => $imgurl,
                'title' => "",
            ];
            if( $user->merchant_status == 1 ){
                $storeData['status'] = 1;
            }else{
                $storeData['status'] = 0;
            }
            $id = $storeModle->saveOne($storeData);
            $storeInfoModel = new StoresInfo();
            if ( isset($info['meiTuan']) ) {
                //            更新美团店铺
                $info['meiTuan']['type'] = 1;
                $info['meiTuan']['uid'] = $uid;
//                $info['meiTuan']['title'] = $info['meiTuan']['title'];
                $storeInfoModel->saveOne($info['meiTuan'], $id);
            }else{
                \DB::table('stores_info')->where('store_id', $id)->where('type', 1)->delete();
            }
            if ( isset($info['eLeMe']) ) {
                //            更新饿了么店铺
                $info['eLeMe']['type'] = 2;
                $info['eLeMe']['uid'] = $uid;
//                $info['eLeMe']['title'] = $info['eLeMe']['title'];
                $storeInfoModel->saveOne($info['eLeMe'], $id);
            }else{
                \DB::table('stores_info')->where('store_id', $id)->where('type', 2)->delete();
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return returnJson(1, "更新失败".$e->getMessage());
        }

        return returnJson();
    }

    public function deleteStore(Request $request){
        $this->uid = \session('uid');
        //店铺id
        $id = intval($request->id);
        if( !$id ){
            return returnJson(1, "参数缺失");
        }
        try {
            DB::beginTransaction();
            \DB::table('stores')->where('uid', $this->uid)->where('id', $id)->update(['is_deleted'=>1, 'updated_at'=>\getDt()]);

            \DB::table('subsidy')->where([['uid', $this->uid], ['store_id', $id]])->update(['is_deleted'=>1, 'updated_at'=>\getDt(), 'status'=>2]);
            
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return returnJson(1, "删除失败");
        }

        return returnJson();
    }

    /**
     * 添加/更新 任务
     * @param Request $request
     */
    public function saveSub(Request $request){
        InterfaceLog('saveSub', '添加/更新任务'.json_encode($request->all()));
        $this->uid = \session('uid');
        $id = $request->id;//任务id
        $uid = $this->uid;//用户id
        $max = $request->max;//满多少金额
        $returnAmount = $request->return_amount;//返金额
        $goodType = $request->goodType??0;//好评类型：0-无需好评，1-5星2图20字
        $stores = $request->storeInfoIds;//店铺id
        $dayCount = $request->dayCount;//每天投放数量
        $day = $request->day;//持续多少天

        if( !$stores || !$max || !$returnAmount ||!$dayCount || !$day ){
            return returnJson(1, '参数错误');
        }

        $user = DB::table('users')->where('id', $this->uid)->first();
        if( !$user ){
            return returnJson(1, '商户错误');
        }
        // if( $user->type != 1 || $user->merchant_status != 1 ){
        //     return returnJson(1, '您还未入驻商户成功');
        // }

        if( $user->frozen_date != null ){
            return returnJson(1, '存在待结算订单，请结算后发布任务');
        }


        $subService = new SubService();
//        添加/更新逻辑
        $res = $subService->addSub($max, $returnAmount, $goodType, $stores, $day, $dayCount, $uid, $id);
        if( $res ){
            return returnJson();
        }

        return returnJson(1, $subService->msg);
    }

    /**
     * 批量加时
     * @param Request $request
     */
   public function addDaySub(Request $request){
        $this->uid = \session('uid');
       $id = $request->id;//任务id字符串
       $day = $request->day;//添加天数
       if( $day <= 0 ){
         return returnJson(1, '请输入天数');
       }

       $user = DB::table('users')->where('id', $this->uid)->first();
        if( !$user ){
            return returnJson(1, '商户错误');
        }

       if( $user->frozen_date != null ){
            return returnJson(1, '存在待结算订单，请结算后更改');
        }

       $ids = explode(',', $id);
       if( count($ids) && isset($ids[0]) && $ids[0] > 0 ){
           foreach ($ids as $key => $value) {
                $sub  = DB::table('subsidy')->where('id', $value)->first();
                $update = [];
                if( strtotime($sub->overdue) < time() ){
                    $update = ['status'=>1, 'start_time'=>date('Y-m-d H:i:s'), 'overdue'=>date('Y-m-d', strtotime("+{$day} day", time())), 'updated_at'=>date('Y-m-d H:i:s')];
                }else{
                    $update = ['status'=>1, 'overdue'=>date('Y-m-d', strtotime("+{$day} day", strtotime($sub->overdue))), 'updated_at'=>date('Y-m-d H:i:s')];
                }
                DB::table('subsidy')->where('id', $value)->update($update);
                
           }
           return returnJson();
       }

       return returnJson(1, '失败');
   }

    /**
     * 终止任务
     * @param Request $request
     */
    public function overSub(Request $request){
        $id = $request->id;//任务id

        $re = DB::table('subsidy')->where('id', $id)->where('status', 1)
            ->update(['status'=>2, 'updated_at'=>date('Y-m-d H:i:s'), 'overdue'=>date('Y-m-d')]);
        if( $re ) return returnJson();

        return returnJson(1, '失败');
    }

    /**
     * 删除任务
     * @param Request $request
     */
    public function delSub(Request $request){
        $id = $request->id;//任务id

        $info = DB::table('subsidy')->where('id', $id)->first();
        if( $info->status == 0 ){
//          真删
            DB::table('subsidy')->where('id', $id)->delete();
            return returnJson();
        }else{
//            假删
            DB::table('subsidy')->where('id', $id)
                ->update(['is_deleted'=>1, 'updated_at'=>date('Y-m-d H:i:s'), 'status'=>2]);
            return returnJson();
        }
    }

    /**
     * 获取任务列表
     * @param Request $request
     */
    public function getList(Request $request){
        $uid = \session('uid');
        $status = $request->input('status', 1);//1-进行中，2-过期
        if( !$uid ){
            return returnJson(1, '参数错误');
        }
        $model = DB::table('subsidy')
            ->join('stores_info', 'subsidy.store_info_id', '=', 'stores_info.id')
            ->join('stores', 'stores_info.store_id', '=', 'stores.id')->where([
                ['subsidy.is_deleted', 0],
                ['subsidy.uid', $uid],
            ]);
        if( $status == 1 ){
            $model->whereIn('subsidy.status', [0, 1]);
        }else{
            $model->where('subsidy.status', 2);
        }
            
        $list = $model->select(['subsidy.*', 'stores_info.title', 'stores.imgurl','stores_info.type as stype'])->get()->toArray();
        foreach ($list as $key => &$value) {
            $value->totalSaleNum = \DB::table('users_orders')->where('sub_id', $value->id)->whereIn('status', [0, 10, 20, 25, 30,35,40,45])->count();
            $value->control = false;
            $value->selected = false;
        }
        return returnJson(0, '', $list);
    }

    /**
     * 任务详情
     * @param Request $request
     */
    public function getOneSub(Request $request){
        $id = $request->id;
        $lat = $request->lat??"";
        $lnt = $request->lnt??"";
        if( !$id ){
            return returnJson(1, '参数错误');
        }
        $data = DB::table('subsidy')->where([
                ['is_deleted', 0],
                ['id', $id],
            ])->first();
        $data->store = DB::table('stores as s')->join('stores_info as si', 's.id', '=', 'si.store_id')
            ->where('si.id', $data->store_info_id)
            ->select(['s.*', 'si.type', 'si.title'])->first();
        if( $lat && $lnt ){
            $data->distance = getDistance($lat, $lnt, $data->store->lat, $data->store->lnt);
        }
        return returnJson(0, '', $data);
    }
}
